<template>
  <!-- 编辑用户弹窗 -->
<el-dialog v-model="editDialogVisible" title="编辑用户" width="400px">
  <el-form :model="editForm" label-width="80px">
    <el-form-item label="用户名">
      <el-input v-model="editForm.username" />
    </el-form-item>
    <el-form-item label="邮箱">
      <el-input v-model="editForm.email" />
    </el-form-item>
    <el-form-item label="角色">
      <el-select v-model="editForm.role" placeholder="请选择角色">
        <el-option v-for="role in roleOptions" :key="role" :label="role" :value="role" />
      </el-select>
    </el-form-item>
    <el-form-item label="状态">
      <el-switch
        v-model="editForm.state"
        :active-value="1"
        :inactive-value="0"
        active-text="启用"
        inactive-text="禁用"
      />
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="editDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="handleEditSave">保存</el-button>
  </template>
</el-dialog>
    <div class="role-management">
      <!-- 页面标题和操作按钮 -->
      <div class="header">
        <h2>用户管理</h2>
        <el-button type="primary" @click="refreshData">刷新数据</el-button>
      </div>
  
      <!-- 用户列表表格 -->
      <el-table 
        :data="tableData" 
        style="width: 100%" 
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="id" label="用户ID" width="150" sortable/>
        <el-table-column prop="username" label="用户名" width="200" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="role" label="角色" width="200">
          <template #default="{ row }">
            <el-tag :type="getRoleTagType(row.role)">
              {{ row.role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="200">
          <template #default="{ row }">
            <el-tag :type="row.state === 1 ? 'success' : 'danger'">
              {{ row.state === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="200">
          <template #default="{ row }">
            
            <el-button 
              link 
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              link 
              :type="row.state === 1 ? 'warning' : 'success'" 
              size="small" 
              @click="handleToggleState(row)"
            >
              {{ row.state === 1 ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </template>
  
  <script setup>

  
  import { ref, onMounted } from 'vue'
  import axios from 'axios'
  import { ElMessage, ElMessageBox } from 'element-plus'
  // 响应式数据
  const tableData = ref([])
  const loading = ref(false)
  const editDialogVisible = ref(false)
const editForm = ref({
  id: null,
  username: '',
  email: '',
  role: '',
  state: 1
})
const roleOptions = [
  '系统管理员', '设备管理员', '学生', '维修人员', '管理员', '教师'
]
  // 获取用户列表
  const getUserList = async () => {
    loading.value = true
    try {
      const response = await axios.get('http://localhost:8080/api/v1/common/listUserInfo')
      
      if (response.data.code === 200) {
        tableData.value = response.data.data
        console.log('用户列表数据:', tableData.value)
      } else {
        ElMessage.error(response.data.message || '获取用户列表失败')
      }
    } catch (error) {
      console.error('获取用户列表失败:', error)
      ElMessage.error('网络请求失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }
  
  // 刷新数据
  const refreshData = () => {
    getUserList()
  }
  
  // 根据角色返回对应的标签类型
  const getRoleTagType = (role) => {
    const roleTypeMap = {
      '系统管理员': 'danger',
      '设备管理员': 'warning', 
      '学生': 'primary',
      '维修人员': 'info',
      '管理员': 'danger',
      '教师': 'success'
    }
    return roleTypeMap[role] || 'default'
  }
  

  // 处理编辑按钮点击
const handleEdit = async (row) => {
  try {
    // 尝试 GET 请求
    const res = await axios.post(`http://localhost:8080/api/v1/users/GetUserInfo/`+row.id)
    if (res.data.code === 200) {
      Object.assign(editForm.value, res.data.data)
      editDialogVisible.value = true
    } else {
      ElMessage.error(res.data.message || '获取用户信息失败')
    }
  } catch (error) {
    ElMessage.error('网络请求失败，请稍后重试')
  }
}

  const handleEditSave = async () => {
  try {
    const currentUserId = Number(localStorage.getItem('userId'))
    // 如果是自己，强制state为原值（不允许改状态）
    if (editForm.value.id === currentUserId) {
      // 可选：给出提示
      ElMessage.warning('不能修改自己的状态，只能修改用户名、邮箱和角色')
      // 只提交原state
      return
    }
    const payload = {
      id: editForm.value.id,
      username: editForm.value.username,
      email: editForm.value.email,
      role: editForm.value.role,
      state: editForm.value.state
    }
    const res = await axios.post('http://localhost:8080/api/v1/users/edit', payload)

    if (res.data.code === 200) {
      ElMessage.success('用户信息更新成功')
      editDialogVisible.value = false
      getUserList()
    } else {
      ElMessage.error(res.data.message || '用户信息更新失败')
    }
  } catch (error) {
    ElMessage.error('网络请求失败，请稍后重试')
  }
}
// 启用/禁用
const handleToggleState = async (row) => {
    if (row.id == localStorage.getItem('userId')) {
    ElMessage.warning('不能修改自己的状态')
    return  
  }
  const action = row.state === 1 ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(
      `确定要${action}用户 ${row.username} 吗？`,
      '操作确认',
      { type: row.state === 1 ? 'warning' : 'success' }
    )
    const res = await axios.post('http://localhost:8080/api/v1/users/edit', {
      id: row.id,
      username: row.username,
      email: row.email,
      role: row.role,
      state: row.state === 1 ? 0 : 1
    })
    if (res.data.code === 200) {
      ElMessage.success(`${action}成功`)
      getUserList()
    } else {
      ElMessage.error(res.data.message || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}
  
  // 组件挂载时获取数据
  onMounted(() => {
    getUserList()
  })
  </script>
  
  <style scoped>
  .role-management {
    padding: 20px;
  }
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .header h2 {
    margin: 0;
    color: #303133;
  }
  </style>